package com.google.androidcamp.session3;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class ElephantTextActivity extends Activity
{
    EditText mTextInput;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // Inflate layout from XML. This is a standard incantation that you'll find
        // at the start of practically every Android activity.
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Obtain references to controls that were inflated from XML.
        mTextInput = (EditText) findViewById(R.id.text_input);

        // Restore saved data from a previous app run
        SharedPreferences data = getSharedPreferences(getClass().getName(), MODE_PRIVATE);
        String savedText = data.getString("saved_text", null);
        if (savedText != null) {
            mTextInput.setText(savedText);
        }
    }

    /** Handler to receive onClick events from buttons.
     *
     * This is defined on a per-button basis inside of layout/main.xml by setting
     * android:onClick="onClick".
     */
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_button:
                mTextInput.setText("");
        }
    }
    
    /** Save persistent data associated with this application for future runs.
     *
     * Note: Per-instance state for each UI element is automatically saved by
     * the default implementation of onSaveInstanceState(Bundle), and automatically
     * restored by onRestoreInstanceState(Bundle). However, this data is discarded
     * when the activity terminates, so we need to store it to disk.
     */
    @Override
    public void onPause()
    {
        super.onPause();
        SharedPreferences data = getSharedPreferences(getClass().getName(), MODE_PRIVATE);
        SharedPreferences.Editor editor = data.edit();
        editor.putString("saved_text", mTextInput.getText().toString());
        editor.commit();
    }
    
}
